// pages/goodsDetail/goodsDetail.js
const app = getApp();
Page({
    data: {
        goodsInfo: null,
        status: 0,
        goodsStock: 0, //商品库存， 会随着用户选择的规格属性变化
        totalPrice: 0,  //商品总价， 会随着用户选择的规格属性变化
        goodsPrice: 0, //商品单价， 会随着用户选择的规格属性变化
        seckillPrice: 0, //商品秒杀单价， 会随着用户选择的规格属性变化
        initStock: 0, //初始库存 没选择任何规格属性时的库存
        initPrice: 0, //初始价格 没选择任何规格属性时的价格
        isShowBox: false,
        isShowShareBox: false,
        needCount: 0,
        selAttribute: '',
        buyGoodsNum: 1,
        attributeID: 0, //所选规格属性价格数组ID
        standardAttr: '',//所选规格属性id拼接
        goodsStandardList: [], //所选商品规格数组
        standardDataList: [],
        timeOutFun: '',
        bannerList: [],
        statusBarHeight: 0,
        isFromStandard: 1 //true表示正常的进入到该页面 false表示从分享或者识别小程序码进入
    },
    onLoad: function (option) {
        console.log(option);
        if (option.scene) {
            let goodsId = decodeURIComponent(option.scene);
            this.setData({
                isFromStandard: 0,
                goodsId: goodsId,
                statusBarHeight: app.globalData.statusBarHeight
            });
            this.getGoodsInfoData(goodsId)
        } else {
            if (option.shareWay == 1) {
                this.addReadData(option.shareUserID, option.goodsId);
            }
            if (option.shareWay == 1 || option.shareWay == 0) {
                this.setData({
                    isFromStandard: 0,
                });
            }
            this.setData({
                goodsId: option.goodsId,
                statusBarHeight: app.globalData.statusBarHeight
            });
            this.getGoodsInfoData(option.goodsId);
        }
    },
    onShow: function () {
        this.setData({
            goodsStandardList: []
        });
    },
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function () {
        clearInterval(this.data.timeOutFun)
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        if (this.data.goodsInfo) {
            if (this.data.goodsInfo.isSeckill == 1) {
                return {
                    title: this.data.goodsInfo.goodsFullName,
                    imageUrl: this.data.goodsInfo.goodsImg,
                    path: '/pages/goodsDetail/goodsDetail?shareUserID=' + app.globalData.userID + '&goodsId=' + this.data.goodsInfo.goodsID + '&shareWay=1'
                }
            } else {
                console.log(this.data.goodsInfo);
                return {
                    title: this.data.goodsInfo.goodsFullName,
                    imageUrl: this.data.goodsInfo.goodsImg,
                    path: '/pages/goodsDetail/goodsDetail?shareUserID=' + app.globalData.userID + '&goodsId=' + this.data.goodsInfo.goodsID + '&shareWay=0'
                }
            }
        } else {
            return {
                title: this.data.goodsInfo.goodsFullName,
                imageUrl: this.data.goodsInfo.goodsImg
            }
        }
    },
    navBackTab: function (e) {
        if (this.data.isFromStandard === 1) {
            wx.navigateBack({
                delta: 1,
            })
        } else {
            wx.switchTab({
                url: '../index/index',
            })
        }
    },
    getGoodsInfoData: function (_goodsID) {
        var that = this;
        var params = {
            userID: app.globalData.userID,
            goodsID: _goodsID
        }
        app.network.requestPost(app.route.ROUTE_GET_GOODS_INFO, params, '正在获取数据', function (res) {
            //res就是我们请求接口返回的数据
            if (res.success) {
                var _goodsInfo = res.context;
                var _initPrice = _goodsInfo.isSeckill == 1 ? _goodsInfo.seckillPrice : _goodsInfo.price; //商品初始价格
                if (_goodsInfo.videoUrl) {
                    _goodsInfo.bannerList.unshift(_goodsInfo.videoUrl);
                }
                that.setData({
                    goodsInfo: _goodsInfo,
                    status: _goodsInfo.status,
                    goodsStock: _goodsInfo.stock,
                    goodsPrice: _initPrice,
                    initStock: _goodsInfo.stock, 
                    initPrice: _initPrice,
                    totalPrice: _goodsInfo.price,
                    bannerList: res.context.bannerList,
                    seckillPrice: _goodsInfo.seckillPrice||0
                });
                if (_goodsInfo.isSeckill == 1) {
                    var timeOutFun = setInterval(function(){
                        var countDownTime = that.seckillCountdownFormat(_goodsInfo.seckillEndTime);
                        var _timeArry = countDownTime.split(":");
                        that.setData({
                            timeArry: _timeArry,
                            timeOutFun: timeOutFun
                        });
                        if (_timeArry[0] == 0 && _timeArry[1] == 0 && _timeArry[2] == 40) {
                            clearInterval(timeOutFun)
                        }
                    }, 1000)
                }
            } else {
                wx.showToast({
                    title: res.msg,
                })
            }
        }, function (res) {
            wx.showToast({
                title: '加载数据失败',
            })
        })
    },
    seckillCountdownFormat: function (value) {
        var currentDate = new Date();
        var year = currentDate.getFullYear();
        var month = currentDate.getMonth() + 1;
        var day = currentDate.getDate();
        var time = year + '/' + month + '/' + day;
        var completeTime = time + ' ' + value;
        var endTime = new Date(completeTime);
        var remain = endTime.getTime() - currentDate.getTime();
        if (remain <= 0) {
            return "";
        }
        var h = parseInt(remain / 1000 / 60 / 60 % 24);
        var m = parseInt(remain / 1000 / 60 % 60);
        var s = parseInt(remain / 1000 % 60);
        return h + ":" + m + ":" + s;
    },
    phoneCallTap: function(e) {
        var _merchantPhone = this.data.goodsInfo.merchantPhone;
        wx.makePhoneCall({
            phoneNumber: _merchantPhone 
        })
    },
    confirmGoods: function(e) {
        if (this.data.status == 0) {
            wx.showToast({
                title: '该商品已下架'
            })
            return;
        }
        var goodsInfo = this.data.goodsInfo;
        if (goodsInfo.isForward == 1) {
            if (goodsInfo.readNum < goodsInfo.readCount) {
                this.setData({
                    needCount: goodsInfo.readCount - goodsInfo.readNum,
                    isShowShareBox: true
                });
                return;
            }
        }
        this.setData({
            totalPrice: this.data.initPrice,
            goodsStock: this.data.initStock,
            selAttribute: '',
            attributeID: 0
        });
        this.getStandardData();
    },
    colseBoxTap: function(e) {
        this.setData({
            isShowBox: false
        });
    },
    closeShareBox: function(e) {
        this.setData({
            isShowShareBox: false
        });
    },
    getStandardData: function () {
        var that = this;
        var params = {
            userID: app.globalData.userID,
            goodsID: that.data.goodsId
        }
        app.network.requestPost(app.route.ROUTE_GET_STANDARD, params, '', function (res) {
            //res就是我们请求接口返回的数据
            if (res.success) {
                var _standardPriceList = res.context.price;
                var _standardDataList = res.context.data;
                if (_standardDataList.length > 0) {//判断商品是否有规格 有规格弹出选择规格的框 反之则直接购买
                    that.setData({
                        isShowBox: true,
                        standardPriceList: _standardPriceList,
                        standardDataList: _standardDataList
                    });
                } else {
                    //没有规格时的 立即购买
                    if (that.data.goodsStock == 0) {
                        wx.showToast({
                            title: '商品库存不足'
                        })
                        return;
                    }
                    that.goSubmitOrder();
                }
            } else {
                wx.showToast({
                    title: res.msg,
                })
            }
        }, function (res) {
            wx.showToast({
                title: '加载数据失败',
            })
        })
    },
    clickMenu: function(e) {
        var _attributeName = ''; //每选中一次规格后的名称字符串组合
        var _attributeID = ''; //每选中一次规格后的规格ID字符串组合
        let selectIndex = e.currentTarget.dataset.rowIndex;
        let attrIndex = e.currentTarget.dataset.colIndex;
        let attributeContent = this.data.standardDataList;
        var count = attributeContent[selectIndex].specDataList.length;
        for (var i = 0; i < count; i++) {
            attributeContent[selectIndex].specDataList[i].isSelect = false
        }
        attributeContent[selectIndex].specDataList[attrIndex].isSelect = true;
        for (var i = 0; i < attributeContent.length; i++) {
            _attributeName += attributeContent[i].standard + ':';
            for (var j = 0; j < attributeContent[i].specDataList.length; j++) {
                if (attributeContent[i].specDataList[j].isSelect) {
                    var tempID = attributeContent[i].specDataList[j].id;
                    _attributeID += tempID;
                    _attributeID += '-';
                    var name = attributeContent[i].specDataList[j].name;
                    _attributeName += name + ';';
                }
            }
        }
        _attributeID = _attributeID.substring(0, _attributeID.length-1);
        console.log(_attributeID, _attributeName);
        for (var item of this.data.standardPriceList) {
            if (_attributeID == item.goodsLastAttr) {
                this.setData({
                    goodsStock: item.stock,
                    goodsPrice: item.price,
                    totalPrice: item.price,
                    attributeID: item.id,
                    standardAttr: _attributeID
                });
            }
        }
        this.setData({
            standardDataList: attributeContent,
            selAttribute: _attributeName,
            buyGoodsNum: 1
        })
    },
    //数量加
    addNumTap: function(e) {
        this.data.buyGoodsNum++;
        this.setData({
            buyGoodsNum: this.data.buyGoodsNum
        });
        this.getTotalPrice(this.data.buyGoodsNum);
    },
    //数量减
    subNumTap: function(e) {
        if (this.data.buyGoodsNum == 1) {
            return;
        }
        this.data.buyGoodsNum--;
        this.setData({
            buyGoodsNum: this.data.buyGoodsNum
        });
        this.getTotalPrice(this.data.buyGoodsNum);
    },
    //计算总价
    getTotalPrice: function (tempBuyGoodsNum) {
        var _totalPrice = this.data.goodsPrice * tempBuyGoodsNum;
        this.setData({
            totalPrice: _totalPrice
        });
    },
    toEvaluationList: function(e) {
        var _markID = e.currentTarget.dataset.markid;
        wx.navigateTo({
            url: '../evaluationList/evaluationList?goodsID=' + this.data.goodsId + '&markID=' + _markID
        })
    },
    confirmOrder: function(e) {
        if (this.data.attributeID == 0) {
            wx.showToast({
                title: '请选择商品规格'
            })
            return;
        }
        if (this.data.goodsStock == 0) {
            wx.showToast({
                title: '库存不足，请重新选规格'
            })
            return;
        }
        this.setData({ isShowBox: false});
        this.goSubmitOrder();
    },
    goSubmitOrder: function() {//拼装参数，跳转到下订单页面
        var _goodsInfo = this.data.goodsInfo;
        var params = {
            goodsID: this.data.goodsId,
            number: this.data.buyGoodsNum,
            standardID: this.data.attributeID,
            subtotal: this.data.totalPrice,
            standard: this.data.standardAttr
        }
        this.data.goodsStandardList.push(params);
        wx.navigateTo({
            url: '../submitOrder/submitOrder?merchantID=' + _goodsInfo.merchantID + '&totalPrice=' + this.data.totalPrice + '&goodsStandardList=' + JSON.stringify(this.data.goodsStandardList) + '&goodsID=' + this.data.goodsId + '&selAttribute=' + this.data.selAttribute + '&goodsPrice=' + this.data.goodsPrice + '&isInvite=' + _goodsInfo.isInvite
        })
    },
    //添加阅读记录接口
    addReadData: function (_shareUserID, _goodsID) {
        var that = this;
        var params = {
            userID: app.globalData.userID,
            shareUserID: _shareUserID,
            goodsID: _goodsID
        }
        app.network.requestPost(app.route.ROUTE_ADD_READ, params, '', function (res) {
            //res就是我们请求接口返回的数据
            if (res.success) {
                //这里没有任何逻辑，该接口用于后台记录转发出之后其他用户点击进入的数据
                console.log("添加成功");
            } 
        }, function (res) {
            wx.showToast({
                title: '加载数据失败',
            })
        })
    },

    goMerchantTap: function(e) {
        wx.navigateTo({
            url: '../merchant/merchant?merchantID=' + this.data.goodsInfo.merchantID + '&isFromStandard=1'
        })
    },

    previewImage: function(e) {
        let currentImage = e.currentTarget.dataset.current;
        wx.previewImage({
            current: currentImage, // 当前显示图片的http链接
            urls: this.data.bannerList // 需要预览的图片http链接列表
        })
    }
})